package com.potato.rxjavademo.rxview

import android.os.Looper
import android.view.View
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.atomic.AtomicBoolean

class ViewClickObservable(val mView: View?) : Observable<Any>() {

    companion object {
        // 事件  防抖 事件 没用
        private val EVENT = Any()
        private var EVENT2: Any?=null
    }
    init {
        EVENT2 = mView
    }

    override fun subscribeActual(observer: Observer<in Any?>) {
        val myListener = MyListener(mView!!, observer)
        observer!!.onSubscribe(myListener)
        mView!!.setOnClickListener(myListener)
    }

    internal class MyListener(val mView:View,val observer: Observer<Any?>):View.OnClickListener, Disposable {
        // boolean  == AtomicBoolean boolean的原子类
        private val isDisposable: AtomicBoolean = AtomicBoolean()

        override fun onClick(v: View?) {
            if (!isDisposed){
                observer!!.onNext(EVENT)
            }
        }

        override fun isDisposed(): Boolean {
            return  isDisposable.get()
        }

        override fun dispose() {
            // 如果没有中断过，才有资格， cas机制
           if(isDisposable.compareAndSet(false,true)){
               //判断是否是主线程
                if (Looper.getMainLooper()== Looper.myLooper()){
                    mView!!.setOnClickListener(null)
                }else{
                    //则需要从子线程切换到主线程
                    //1、通过创建handler的方式进行切换线程
                    /*object : Handler(Looper.getMainLooper()) {
                        override fun handleMessage(msg: Message) {
                            super.handleMessage(msg)
                            mView!!.setOnClickListener(null)
                        }
                    }
                    */
                    //2、通过RxJava的源码分析 AndroidSchedulers.mainThread() 也是从子线程中去切换回到主线程
                    AndroidSchedulers.mainThread().scheduleDirect(object:Runnable{
                        override fun run() {
                            mView!!.setOnClickListener(null)
                        }
                    })
                }
           }
        }
    }


}